<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <text class="nav-title">搭子请求</text>
    </view>

    <!-- 标签页切换 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        :class="{'active': activeTab === 'received'}"
        @tap="activeTab = 'received'"
      >
        <text>收到的请求</text>
        <view class="tab-line" v-show="activeTab === 'received'"></view>
      </view>
      <view 
        class="tab-item" 
        :class="{'active': activeTab === 'sent'}"
        @tap="activeTab = 'sent'"
      >
        <text>发送的请求</text>
        <view class="tab-line" v-show="activeTab === 'sent'"></view>
      </view>
      <view 
        class="tab-item" 
        :class="{'active': activeTab === 'myPartners'}"
        @tap="activeTab = 'myPartners'"
      >
        <text>我的搭子</text>
        <view class="tab-line" v-show="activeTab === 'myPartners'"></view>
      </view>
    </view>

    <!-- 请求列表 -->
    <scroll-view scroll-y class="request-list">
      <!-- 收到的请求 -->
      <view v-if="activeTab === 'received'">
        <view v-if="receivedRequests.length > 0">
          <view class="request-item card-shadow" 
                v-for="(request, index) in receivedRequests" 
                :key="index">
            <view class="avatar">
              <text class="avatar-emoji">{{request.avatar}}</text>
            </view>
            <view class="request-info">
              <view class="user-info">
                <text class="username">{{request.name || '加载中...'}}</text>
                <text class="major">{{request.senderMajor || '加载中...'}}</text>
              </view>
              <text class="target-school">目标院校：{{request.targetSchool}}</text>
              <text class="time">{{request.time}}</text>
            </view>
            <view class="action-buttons">
              <button class="accept-btn" @tap="handleRequest(request.id, 'accept')">接受</button>
              <button class="reject-btn" @tap="handleRequest(request.id, 'reject')">婉拒</button>
            </view>
          </view>
        </view>
        <view v-else class="empty-state">
          <text class="icon">📭</text>
          <text class="empty-text">暂无收到的请求</text>
        </view>
      </view>

      <!-- 发送的请求 -->
      <view v-if="activeTab === 'sent'">
        <view v-if="sentRequests.length > 0">
          <view class="request-item card-shadow" 
                v-for="(request, index) in sentRequests" 
                :key="index">
            <view class="avatar">
              <text class="avatar-emoji">{{request.avatar}}</text>
            </view>
            <view class="request-info">
              <view class="user-info">
                <text class="username">{{request.sendername || '加载中...'}}</text>
                <text class="major">{{request.senderMajor || '加载中...'}}</text>
              </view>
              <text class="target-school">目标院校：{{request.targetSchool}}</text>
              <text class="time">{{request.time}}</text>
            </view>
            <view class="status" :class="request.status">
              {{getStatusText(request.status)}}
            </view>
          </view>
        </view>
        <view v-else class="empty-state">
          <text class="icon">📤</text>
          <text class="empty-text">暂无发送的请求</text>
        </view>
      </view>
      
      <!-- 我的搭子 -->
      <view v-if="activeTab === 'myPartners'">
        <view v-if="myPartners.length > 0">
          <view class="partner-item card-shadow" 
                v-for="(partner, index) in myPartners" 
                :key="index">
            <view class="avatar">
              <text class="avatar-emoji">{{partner.avatar}}</text>
            </view>
            <view class="partner-info">
              <view class="user-info">
                <text class="name">{{partner.name}}</text>
                <text class="major">{{partner.major}}</text>
              </view>
              <text class="target-school">目标院校：{{partner.targetSchool}}</text>
              <text class="partner-since">搭子关系：{{partner.partnerSince}}</text>
            </view>
            <view class="partner-actions">
              <button class="chat-btn" @tap="navigateToChat(partner.id)">
                <text class="chat-icon">💬</text>
              </button>
              <button class="more-btn" @tap="showPartnerOptions(partner)">
                <text>⋮</text>
              </button>
            </view>
          </view>
        </view>
        <view v-else class="empty-state">
          <text class="icon">👥</text>
          <text class="empty-text">暂无搭子，快去添加吧</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 搭子选项菜单 -->
    <view class="partner-options-modal" v-if="showOptions">
      <view class="options-backdrop" @tap="showOptions = false"></view>
      <view class="options-content">
        <view class="option-item" @tap="navigateToPartnerDetail">
          <text class="option-icon">👤</text>
          <text>查看详情</text>
        </view>
        <view class="option-item" @tap="navigateToChat(selectedPartner.id)">
          <text class="option-icon">💬</text>
          <text>发送消息</text>
        </view>
        <view class="option-item warning" @tap="confirmUnbind">
          <text class="option-icon">🔄</text>
          <text>解除绑定</text>
        </view>
        <view class="option-item cancel" @tap="showOptions = false">
          <text>取消</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const activeTab = ref('received')
const showOptions = ref(false)
const selectedPartner = ref(null)

const receivedRequests = ref([])
const sentRequests = ref([])
const myPartners = ref([])

// 假设当前用户 ID 为 1，实际应用中需要动态获取
const userId = 1;

const getStatusText = (status) => {
  const statusMap = {
    'pending': '等待回复',
    'accepted': '已接受',
    'rejected': '已婉拒'
  }
  return statusMap[status]
}

const handleRequest = (requestId, action) => {
  const actionText = action === 'accept' ? '接受' : '婉拒'
  uni.showModal({
    title: '确认',
    content: `确定要${actionText}这个搭子请求吗？`,
    success: (res) => {
      if (res.confirm) {
        // 调用后端接口处理请求
        uni.request({
          url: `http://localhost:8080/api/partner/request/handle/${requestId}/${action}`,
          method: 'PUT',
          success: (response) => {
            if (response.statusCode === 200) {
              // 更新本地数据
              if (action === 'accept') {
                // 假设接受请求后将请求加入 myPartners
                const request = receivedRequests.value.find(req => req.id === requestId)
                myPartners.value.push({
                  id: request.id,
                  avatar: request.avatar,
                  name: request.name,
                  major: request.major,
                  targetSchool: request.targetSchool,
                  partnerSince: '刚刚'
                })
              }
              receivedRequests.value = receivedRequests.value.filter(req => req.id !== requestId)
              uni.showToast({
                title: `已${actionText}请求`,
                icon: 'success'
              })
            } else {
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          },
          fail: (err) => {
            console.error('操作请求失败', err)
            uni.showToast({
              title: '操作失败',
              icon: 'none'
            })
          }
        })
      }
    }
  })
}

const navigateToChat = (partnerId) => {
  // 关闭选项菜单（如果打开）
  showOptions.value = false
  // 导航到聊天页面
  uni.navigateTo({
    url: `/pages/partner/chat?id=${partnerId}`
  })
}

const showPartnerOptions = (partner) => {
  selectedPartner.value = partner
  showOptions.value = true
}

const navigateToPartnerDetail = () => {
  showOptions.value = false
  // 导航到搭子详情页面
  uni.navigateTo({
    url: `/pages/partner/detail?id=${selectedPartner.value.id}`
  })
}

const confirmUnbind = () => {
  showOptions.value = false
  uni.showModal({
    title: '解除绑定',
    content: `确定要解除与"${selectedPartner.value.name}"的搭子关系吗？`,
    success: (res) => {
      if (res.confirm) {
        // 调用后端接口解除绑定，这里需要后端提供相应接口
        uni.showToast({
          title: '该功能暂未实现',
          icon: 'none'
        })
      }
    }
  })
}

// 获取用户信息的方法
const getUserInfo = (senderId) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `http://localhost:8080/api/user/${senderId}`,
      method: 'GET',
      success: (response) => {
        if (response.statusCode === 200) {
          resolve(response.data);
		  console.log(response)
        } else {
          reject(new Error('获取用户信息失败'));
        }
      },
	  
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 在组件挂载时获取数据
onMounted(async () => {
  // 模拟获取收到的请求
  uni.request({
    url: `http://localhost:8080/api/partner/requests/received/${userId}`,
    method: 'GET',
    success: async (response) => {
      if (response.statusCode === 200) {
        receivedRequests.value = response.data;
        for (const request of receivedRequests.value) {
          try {
            const userInfo = await getUserInfo(request.senderId);
            request.senderUsername = userInfo.username;
            request.senderMajor = userInfo.major;
          } catch (error) {
            console.error('获取发送者信息失败', error);
          }
        }
      }
    },
    fail: (err) => {
      console.error('获取收到的请求失败', err);
    }
  })

  // 模拟获取发送的请求
  uni.request({
    url: `http://localhost:8080/api/partner/requests/sent/${userId}`,
    method: 'GET',
    success: async (response) => {
      if (response.statusCode === 200) {
        sentRequests.value = response.data;
        for (const request of sentRequests.value) {
          try {
            const userInfo = await getUserInfo(request.senderId);
            request.senderUsername = userInfo.username;
            request.senderMajor = userInfo.major;
          } catch (error) {
            console.error('获取发送者信息失败', error);
          }
        }
      }
    },
    fail: (err) => {
      console.error('获取发送的请求失败', err);
    }
  })

  // 模拟获取我的搭子
  uni.request({
    url: `http://localhost:8080/api/partner/list/${userId}`,
    method: 'GET',
    success: (response) => {
      if (response.statusCode === 200) {
        myPartners.value = response.data;
      }
    },
    fail: (err) => {
      console.error('获取我的搭子失败', err);
    }
  })
})
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.nav-bar {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #A8BF8F 0%, #8FA876 100%);
  padding: 0 30rpx;
}

.nav-title {
  color: #fff;
  font-size: 36rpx;
  font-weight: 600;
}

.tabs {
  display: flex;
  background-color: #fff;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx 0;
  position: relative;
}

.tab-item.active {
  color: #8FA876;
  font-weight: 500;
}

.tab-line {
  position: absolute;
  bottom: 0;
  width: 40rpx;
  height: 4rpx;
  background: #8FA876;
  border-radius: 2rpx;
}

.request-list {
  padding: 20rpx;
}

.request-item, .partner-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  border: 3rpx solid #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.avatar-emoji {
  font-size: 50rpx;
  line-height: 1;
}

.request-info, .partner-info {
  flex: 1;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 6rpx;
}

.username {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.major {
  font-size: 24rpx;
  color: #666;
  background: #f0f2f5;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.target-school {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 6rpx;
}

.time, .partner-since {
  font-size: 24rpx;
  color: #999;
}

.partner-since {
  background: #f6ffed;
  color: #52c41a;
  display: inline-block;
  padding: 2rpx 10rpx;
  border-radius: 10rpx;
  margin-top: 6rpx;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.accept-btn, .reject-btn {
  font-size: 26rpx;
  padding: 8rpx 24rpx;
  border-radius: 30rpx;
  border: none;
}

.accept-btn {
  background: linear-gradient(135deg, #A8BF8F 0%, #8FA876 100%);
  color: #fff;
}

.reject-btn {
  background: #f5f5f5;
  color: #666;
}
</style>